package com.example.easyscript.common.minio;

import cn.hutool.core.util.RandomUtil;

import com.example.easyscript.common.minio.bo.MinioBo;
import com.example.easyscript.common.minio.bo.MinioConstants;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class MinioUtil {

    @Resource
    private MinioTemplate minioTemplate;
    @Resource
    private MinioBo minioB;

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public Map<String, String> uploadFile(MultipartFile file) {
        String bucketName = minioB.getBucket();
        String originalFilename = file.getOriginalFilename();
        String prefix = getPrefix();
        String newName = prefix + originalFilename;
        String fileUrl = this.fileUrl(newName);
        Map<String, String> resultMap = new HashMap<>(10);
        resultMap.put("fileName", newName);
        resultMap.put("fileUrl", fileUrl);
        try {
            minioTemplate.putObject(bucketName, newName, file.getInputStream(), file.getSize(), this.getFileType(file));
        } catch (Exception e) {
            log.error("上传失败", e);
        }
        return resultMap;
    }

    private String getPrefix() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))
                + "_" + RandomUtil.randomString(10) + "_";
    }


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public Map<String, String> uploadLocalFile(File file) throws Exception {
        String bucketName = MinioConstants.XS_PRODUCE_BUCKET_NAME;
        String originalFilename = file.getName();
        String prefix = getPrefix();
        String newName = prefix + originalFilename;

        Map<String, String> resultMap = new HashMap<>(10);
        resultMap.put("bucketName", bucketName);
        resultMap.put("fileName", newName);
        try {
            minioTemplate.putObject(bucketName, newName, new FileInputStream(file));
        } catch (Exception e) {
            log.error("上传失败", e);
            throw new Exception("minioError");
        }
        return resultMap;
    }

    /**
     * 获取文件路径
     *
     * @param objectName
     * @return
     */
    public String fileUrl(String objectName) {
        String bucketName = MinioConstants.XS_PRODUCE_BUCKET_NAME;
        String url = null;
        try {
            url = minioTemplate.getObjectURL(bucketName, objectName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 获取文件路径，去掉日期过期信息
     *
     * @param objectName
     * @return
     */
    public String fileUrlShort(String objectName) {
        String bucketName = MinioConstants.XS_PRODUCE_BUCKET_NAME;
        String url = null;
        try {
            url = minioTemplate.getObjectURL(bucketName, objectName);
            int index = url.indexOf("?");
            if (index != -1) {
                url = url.substring(0, index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    /**
     * 根据文件路径得到预览文件绝对地址
     *
     * @param fileName 文件路径
     * @return
     */
    public String getPreviewFileUrl(String fileName) {

        String bucketName = MinioConstants.XS_PRODUCE_BUCKET_NAME;
        String url = null;
        try {
            MinioClient minioClient = minioTemplate.getMinioClient();
            url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(fileName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }


    private final static String IMAGE_TYPE = "image/";
    private final static String AUDIO_TYPE = "audio/";
    private final static String VIDEO_TYPE = "video/";
    private final static String APPLICATION_TYPE = "application/";
    private final static String TXT_TYPE = "text/";

    private String getFileType(MultipartFile multipartFile) {

        try {

//            String type = FileTypeUtil.getType(multipartFile.getInputStream());
            String originalFilename = multipartFile.getOriginalFilename();
            String type = originalFilename.substring(originalFilename.lastIndexOf('.') + 1);
            log.info("文件类型：{}", type);
            if (type.equalsIgnoreCase("JPG") || type.equalsIgnoreCase("JPEG") || type.equalsIgnoreCase("GIF") || type.equalsIgnoreCase("PNG") || type.equalsIgnoreCase("BMP") || type.equalsIgnoreCase("PCX") || type.equalsIgnoreCase("TGA") || type.equalsIgnoreCase("PSD") || type.equalsIgnoreCase("TIFF")) {
                return IMAGE_TYPE + type;
            }

            if (type.equalsIgnoreCase("mp3") || type.equalsIgnoreCase("OGG") || type.equalsIgnoreCase("WAV") || type.equalsIgnoreCase("REAL") || type.equalsIgnoreCase("APE") || type.equalsIgnoreCase("MODULE") || type.equalsIgnoreCase("MIDI") || type.equalsIgnoreCase("VQF") || type.equalsIgnoreCase("CD")) {
                return AUDIO_TYPE + type;
            }

            if (type.equalsIgnoreCase("mp4") || type.equalsIgnoreCase("avi") || type.equalsIgnoreCase("MPEG-1") || type.equalsIgnoreCase("RM") || type.equalsIgnoreCase("ASF") || type.equalsIgnoreCase("WMV") || type.equalsIgnoreCase("qlv") || type.equalsIgnoreCase("MPEG-2") || type.equalsIgnoreCase("MPEG4") || type.equalsIgnoreCase("mov") || type.equalsIgnoreCase("3gp")) {
                return VIDEO_TYPE + type;
            }

            if (type.equalsIgnoreCase("doc")
                    || type.equalsIgnoreCase("docx")
                    || type.equalsIgnoreCase("ppt")
                    || type.equalsIgnoreCase("pptx")
                    || type.equalsIgnoreCase("xls")
                    || type.equalsIgnoreCase("xlsx")
                    || type.equalsIgnoreCase("zip")
                    || type.equalsIgnoreCase("jar")) {
                return APPLICATION_TYPE + type;
            }

            if (type.equalsIgnoreCase("txt")) {
                return TXT_TYPE + type;
            }

            if (type.equalsIgnoreCase("pdf")) {
                return APPLICATION_TYPE + type;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }
}
